<template>
  <div class="chat-body">
    <div class="chat-body-center">
      <div ref="chatContent" class="chat-content">
        <div
          class="chat-content-item"
          v-for="(item, index) in chatList"
          :key="index"
        >
          <!--  -->
          <div
            class="chat-content-item-right chat-content-common"
            v-if="item.role === 'user'"
          >
            <div class="chat-content-item-content">
              <div class="chat-content-item-content-text">
                {{ item.content }}
              </div>
            </div>
            <div class="chat-content-item-avatar">
              <a-avatar :size="50">
                <template #icon>
                  <img v-if="true" src="../../assets/images/bg.jpg" alt="" />
                  <UserOutlined v-else
                /></template>
              </a-avatar>
            </div>
          </div>
          <!--  -->
          <div
            class="chat-content-item-left chat-content-common"
            v-if="item.role === 'assistant'"
          >
            <div class="chat-content-item-avatar">
              <a-avatar :size="50">
                <template #icon>
                  <img
                    v-if="false"
                    src="../../../assets/images/bg.jpg"
                    alt="" />
                  <UserOutlined v-else
                /></template>
              </a-avatar>
            </div>
            <div class="chat-content-item-content">
              <div class="chat-content-item-content-text">
                {{ item.content }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <a-textarea
          class="chat-input-textarea"
          v-model:value="sendValue"
          placeholder="发送消息"
          :rows="4"
          :auto-size="{ minRows: 4, maxRows: 5 }"
        >
        </a-textarea>
        <a-button
          class="send-btn"
          type="primary"
          shape="circle"
          @click="sendMsg"
        >
          <template #icon>
            <ArrowUpOutlined />
          </template>
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { ArrowUpOutlined, UserOutlined } from "@ant-design/icons-vue";
import { getChatHistory, chatWithDeepseek } from "@/api/aiClient";
import { useStreaming } from "/src/hooks/useStreaming.js";

const { messages, streamResponse } = useStreaming();
const sendValue = ref("");
const chatContent = ref("");
const chatList = ref([]);
let eventSource = null; // EventSource 实例
onMounted(() => {
  getChatHistoryFun();
});
const getChatHistoryFun = async () => {
  try {
    let result = await getChatHistory({ chatId: 1 });
    console.log("result", result);

    if (result.status == 200) {
      chatList.value = result.rows;
      // result.rows.forEach((item) => {
      //   chatList.value.push({
      //     ...item,
      //     content: item.content.replace(/\n/g, "<br>"),
      //   });
      // });
      console.log("chatList", chatList.value);
      scrollToBottom();
    }
  } catch (error) {}
};

const sendMsg = async () => {
  if (!chatContent.value || !chatList.value || !sendValue.value) {
    // console.error("必要的值未定义");
    return;
  }

  console.log("sendMsg", chatContent.value);
  // 清空输入框
  const inputValue = sendValue.value;
  sendValue.value = "";
  scrollToBottom();
  chatList.value.push({
    aiId: 1,
    content: inputValue,
    role: "user",
  });

  nextTick(() => {
    chatContent.value.scrollTo({
      top: chatContent.value.scrollHeight,
      behavior: "smooth",
    });
  });

  // 关闭之前的 EventSource 连接
  if (eventSource) {
    eventSource.close();
  }
  const params = {
    aiId: 1,
    chatId: 1,
    message: inputValue,
  };
  // 调用流式传输工具函数
  await streamResponse(
    "/api/aiClient/chatWithDeepseek",
    params,
    (chunk) => {
      // 更新模型回复
      console.log(22222, chunk);
      // 更新模型回复
      if (chunk) {
        const lastMessage = chatList.value[chatList.value.length - 1];
        if (lastMessage.role === "assistant") {
          lastMessage.content += chunk; // 追加内容
        } else {
          chatList.value.push({ role: "assistant", content: chunk }); // 新增消息
        }
        // 滚动到底部
        scrollToBottom();
      }
    },
    (error) => {
      console.error("Error:", error);
    }
  );
  console.log(22222, chatList.value[chatList.value.length - 1]);

  // // 监听错误事件
  // eventSource.onerror = (event) => {
  //   console.error("EventSource failed:", event);
  //   eventSource.close();
  // };
  // try {
  //   let result = await chatWithDeepseek({
  //     aiId: 1,
  //     chatId: 1,
  //     message: inputValue,
  //   });
  //   if (result.status == 200) {
  //     // // 清空发送框的值
  //     // sendValue.value = "";
  //     getChatHistoryFun();
  //   }
  // } catch (error) {}
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTo({
        top: chatContent.value.scrollHeight,
        behavior: "smooth",
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.chat-body {
  // display: flex;
  position: relative;
  width: 100%;
  height: 100%;
  .chat-body-center {
    display: flex;
    height: 100%;
    flex-direction: column;
    // justify-content: center;
    align-items: center;
    .chat-content {
      width: 90%;
      height: 80%;
      overflow: scroll;
      .chat-content-item {
        display: flex;
        font-size: 0;
        width: 100%;
        .chat-content-common {
          display: flex;
          width: 95%;
          // max-width: 100%; /* 限制子元素的最大宽度 */
          flex-wrap: wrap; /* 允许子元素换行 */
          align-items: center;
          margin: 1.25rem 0.625rem;
        }
        .chat-content-item-left {
          justify-content: flex-start; /* 将所有项目对齐到主轴的末尾 */
        }
        .chat-content-item-right {
          justify-content: flex-end; /* 将所有项目对齐到主轴的末尾 */
        }
        .chat-content-item-avatar {
          // display: flex;
          // // width: 100%;
          // align-items: center;
          // justify-content: center;
          margin: 1.25rem;
        }
        .chat-content-item-content {
          // width: 70%;
          max-width: 75%;
          border-radius: 0.625rem;
          padding: 0.625rem;
          box-shadow: 0 0px 0.2rem rgba(0, 0, 0, 0.7);
          .chat-content-item-content-text {
            // max-width: 70%;
            white-space: pre-wrap; /* 保持文本的换行和空格 */
            // white-space: normal; /* 默认行为，文字自动换行 */
            word-wrap: break-word; /* 允许长单词或 URL 换行 */
            overflow-wrap: break-word; /* 更现代的属性，效果与 word-wrap 相同 */
            font-size: 1rem;
          }
        }
      }
    }

    .chat-input {
      display: flex;
      position: absolute;
      width: 80%;
      bottom: 1.875rem;
      .chat-input-textarea {
        // width: 80%;
      }
      .send-btn {
        position: absolute;
        right: 1.25rem;
        bottom: 1.25rem;
      }
    }
    @media screen and (max-width: 1000px) {
      .chat-content {
        width: 100%;
      }
      .chat-input {
        width: 97%;
      }
    }
  }
}
</style>
